package com.wfh.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wfh.common.BaseResponse;
import com.wfh.common.ResultUtils;
import com.wfh.constant.UserConstant;
import com.wfh.model.dto.user.UserLoginRequest;
import com.wfh.model.entity.User;
import com.wfh.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * @Author FengHuan Wang
 * @Date 2025/4/18 17:30
 * @Version 1.0
 */
@RestController
@Slf4j
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户登录接口
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> login(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
        String userName = userLoginRequest.getUserName();
        String userPassword = userLoginRequest.getUserPassword();
        if (StrUtil.isBlank(userName) || StrUtil.isBlank(userPassword)){
            throw new RuntimeException("用户名或密码为空");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername, userName).eq(User::getUserPassword, userPassword);
        User user = userService.getOne(queryWrapper, false);
        if (user == null){
            throw new RuntimeException("用户不存在");
        }
        request.getSession().setAttribute(UserConstant.LOGIN_USER, user);
        return ResultUtils.success(user);
    }

    /**
     * 获取当前登录用户
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<User> getLoginUser(HttpServletRequest request){
        User loginUser = (User) request.getSession().getAttribute(UserConstant.LOGIN_USER);
        return ResultUtils.success(loginUser);
    }
}
